package com.tfjybj.itoo.exam.provider.controller;

import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.TemplateEntity;
import com.tfjybj.itoo.exam.model.ExamPaperModel;
import com.tfjybj.itoo.exam.model.QuestionTypeModel;
import com.tfjybj.itoo.exam.model.TemplateInfoModel;
import com.tfjybj.itoo.exam.model.TemplateModel;
import com.tfjybj.itoo.exam.provider.service.TemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * TemplateController
 * template表
 *
 * @author 任晓帅
 * @version 2.0.0
 * @since 2.0.0 2018-11-15 19:40:28
 */
@Api(tags = {"template表接口"})
@RequestMapping(value = "/template")
@RestController
@Slf4j
public class TemplateController {

    @Resource
    private TemplateService templateService;

    //region 模板生成：基本增删改

    /**
     * 添加
     *
     * @param model TemplateModel
     * @return 添加的结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "添加")
    @PostMapping(value = {"/create"})
    public ItooResult create(@RequestBody TemplateModel model) {
        if (StringUtils.isEmpty(model.getName())) {
            return ItooResult.build(ItooResult.FAIL, "name为空");
        }
        if (StringUtils.isEmpty(model.getCourseId())) {
            return ItooResult.build(ItooResult.FAIL, "courseId为空");
        }
        if (StringUtils.isEmpty(model.getStatus())) {
            return ItooResult.build(ItooResult.FAIL, "status为空");
        }
        if (StringUtils.isEmpty(model.getScore())) {
            return ItooResult.build(ItooResult.FAIL, "score为空");
        }
        if (StringUtils.isEmpty(model.getTotalNumber())) {
            return ItooResult.build(ItooResult.FAIL, "totalNumber为空");
        }
        if (StringUtils.isEmpty(model.getOrganizingType())) {
            return ItooResult.build(ItooResult.FAIL, "organizingType为空");
        }
        TemplateEntity templateEntity = new TemplateEntity();
        BeanUtils.copyProperties(model, templateEntity);
        templateService.save(templateEntity);
        return ItooResult.build(ItooResult.SUCCESS, "添加成功");
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return ItooResult 是否删除成功
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id删除（单个）")
    @DeleteMapping(value = {"/delete/{id}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        templateService.removeById(id);
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return ItooResult 批量删除是否成功结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping(value = {"/deleteByIds"})
    @ApiParam(value = "ids", required = true)
    public ItooResult deleteByIds(@RequestBody List<String> ids) {
        templateService.removeByIds(ids);
        return ItooResult.build(ItooResult.SUCCESS, "批量删除成功");
    }

    /**
     * 修改
     *
     * @param model TemplateModel
     * @return 修改后的结果
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id修改template")
    @PutMapping(value = {"/modify"})
    public ItooResult modify(@RequestBody TemplateModel model) {
        if (StringUtils.isEmpty(model.getName())) {
            return ItooResult.build(ItooResult.FAIL, "name为空");
        }
        if (StringUtils.isEmpty(model.getCourseId())) {
            return ItooResult.build(ItooResult.FAIL, "courseId为空");
        }
        if (StringUtils.isEmpty(model.getStatus())) {
            return ItooResult.build(ItooResult.FAIL, "status为空");
        }
        if (StringUtils.isEmpty(model.getScore())) {
            return ItooResult.build(ItooResult.FAIL, "score为空");
        }
        if (StringUtils.isEmpty(model.getTotalNumber())) {
            return ItooResult.build(ItooResult.FAIL, "totalNumber为空");
        }
        if (StringUtils.isEmpty(model.getOrganizingType())) {
            return ItooResult.build(ItooResult.FAIL, "organizingType为空");
        }
        TemplateEntity templateEntity = new TemplateEntity();
        BeanUtils.copyProperties(model, templateEntity);
        templateService.updateById(templateEntity);
        return ItooResult.build(ItooResult.SUCCESS, "修改成功");
    }

    /**
     * 根据id查找Template
     *
     * @param id 主键id
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = {"/findById/{id}"})
    public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        TemplateEntity templateEntity = templateService.getById(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateEntity);
    }

    /**
     * 分页查询所有Template
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "分页查询所有Template")
    @GetMapping(value = {"/queryPageAll/{pageNo}/{pageSize}"})
    public ItooResult queryPageAll(@ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
                                   @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize) {
        PageInfo<TemplateEntity> templates = templateService.queryPageAll(pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templates);
    }

    /**
     * 根据模板名称模糊查询template
     *
     * @param name     模板名称
     * @param pageNo   页码
     * @param pageSize 页数
     * @return 模糊查询的template
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据模板名称模糊查询template", notes = "分页根据模板名称模糊查询template")
    @GetMapping(value = "queryTemplateByLikeName/{pageNo}/{pageSize}")
    public ItooResult queryTemplateByLikeName(@RequestParam(required = false, defaultValue = "") String name,
                                              @ApiParam(value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
                                              @ApiParam(value = "记录数", required = true, example = "10") @PathVariable Integer pageSize
            , @RequestParam(required = false, defaultValue = "") String courseId) {
        PageInfo<TemplateModel> templateList = templateService.queryByLikeName(name, pageNo, pageSize, courseId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateList);
    }
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 分页查询操作人所有template
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @param operator 操作人
     * @param courseId 课程id
     * @return 查询的template
     * @author 邓立瑶
     * @since 2.0.0 2018年11月13日14:15:26
     */
    @ApiOperation(value = "根据操作人查询所有模板", notes = "根据操作人查询所有模板")
    @GetMapping(value = "queryByOperator/{operator}/{pageNo}/{pageSize}")
    public ItooResult queryByOperator(
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
            @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize,
            @RequestParam(required = false, defaultValue = "") String courseId) {
        PageInfo<TemplateModel> result = templateService.queryByOperator(operator, pageNo, pageSize, courseId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", result);
    }

    /**
     * 根据课程id,操作人,模板使用状态查询所有模板
     *
     * @param operator   操作人
     * @param courseId   课程id
     * @param tempStatus 模板状态
     * @return 返回符合条件的集合
     * @author maying
     * @since 2019-1-26 10:36:05
     */
    @ApiOperation(value = "根据课程id,操作人,模板使用状态查询所有模板")
    @GetMapping(value = "selectAllTemplate/{operator}/{courseId}/{tempStatus}")
    public ItooResult selectAllTemplate(@PathVariable String operator, @PathVariable String courseId, @PathVariable Integer tempStatus) {
        return ItooResult.build(ItooResult.SUCCESS, "查询成功!", templateService.selectAllTemplate(operator, courseId, tempStatus));
    }

    /**
     * 根据级联条件查询template信息（操作人、组卷方式、开始时间、结束时间）
     *
     * @param operator       操作人
     * @param organizingType 组卷方式
     * @param startTime      开始时间
     * @param endTime        结束时间
     * @return template信息
     * @author 邓立瑶
     * @since 1.0.0 2018-10-25 11:00:20
     */
    @ApiOperation(value = "根据级联条件查询template信息")
    @GetMapping(value = "queryByTemplateTypeModel/{operator}/{organizingType}/{startTime}/{endTime}")
    public ItooResult queryByTemplateTypeModel(
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @ApiParam(value = "组卷方式", required = true) @PathVariable String organizingType,
            @ApiParam(value = "开始时间", required = true) @PathVariable String startTime,
            @ApiParam(value = "结束时间", required = true) @PathVariable String endTime
    ) {
        List<TemplateModel> templateEntityList = templateService.queryByTemplateTypeModel(operator, organizingType, startTime, endTime);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateEntityList);
    }

    /**
     * 查询所有组卷方式queryAllOrganization
     *
     * @return 查询的organizationType
     * @author 邓立瑶
     * @since 2.0.0 2018-11-13 15:58:56
     */
    @ApiOperation(value = "查询所有组卷方式queryAllOrganization")
    @GetMapping(value = "queryAllOrganization")
    public ItooResult queryAllOrganization() {
        List<TemplateEntity> templateEntityListList = templateService.queryAllOrganization();
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateEntityListList);
    }

    /**
     * 根据组卷方式和操作人查询queryByMethodOperator
     *
     * @return 查询的template
     * @author 邓立瑶
     * @since 2.0.0 2018年11月23日16:57:52
     */
    @ApiOperation(value = "根据组卷方式和操作人查询")
    @GetMapping(value = "queryByMethodOperator/{operator}/{organizingType}")
    public ItooResult queryByMethodOperator(
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @ApiParam(value = "组卷方式", required = true) @PathVariable String organizingType
    ) {
        List<TemplateEntity> templateEntityList = templateService.queryByMethodOperator(operator, organizingType);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateEntityList);
    }
    /**
     * 根据组卷方式和操作人查询queryByMethodOperatorandOrganizingType
     *
     * @return 查询的template
     * @author 杨海云
     * @since 2.0.0 2018年11月23日16:57:52
     */
    @ApiOperation(value = "根据组卷方式和操作人查询")
    @GetMapping(value = "queryByMethodOperatorandOrganizingType/{operator}/{organizingType}")
    public ItooResult queryByMethodOperatorandOrganizingType(
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @ApiParam(value = "组卷方式", required = true) @PathVariable String organizingType
    ) {
        List<TemplateModel> templateEntityList = templateService.queryByMethodOperatorandOrganizingType(operator, organizingType);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateEntityList);
    }
    /**
     * 添加template
     *
     * @return 添加template
     * @author 杨海云
     * @since 2.0.0 2018年11月25日16:57:52
     */
    @ApiOperation(value = "添加template")
    @PostMapping(value = "/insertTemplate")
    public ItooResult insertTemplate(@RequestBody TemplateModel model) {
//        templateService.insertTemplate(model);
//        return ItooResult.build(ItooResult.SUCCESS, "添加成功");
        String templateId = templateService.insertTemplate(model);
        if (!"null".equals(templateId)) {
            return ItooResult.build(ItooResult.SUCCESS, "添加成功!", templateId);
        } else {
            return ItooResult.build(ItooResult.FAIL, "添加失败!");
        }
    }

    /**
     * 添加固定抽题template--随堂小练用
     *
     * @return 固定抽题抽出的试卷--随堂小练用
     * @author 任蒙蒙
     * @since 2.0.0 2019年1月29日22:20:07
     */
    @ApiOperation(value = "添加固定抽题template--随堂小练用")
    @PostMapping(value = "/insertTemplateForFix")
    public ItooResult insertTemplateForFix(@RequestBody TemplateModel model) {
        ExamPaperModel examPaperModel = templateService.insertTemplateForFix(model);
        return ItooResult.build(ItooResult.SUCCESS, "添加成功", examPaperModel);
    }

    /**
     * 根据templateId
     *
     * @return 返回selTempModel
     * @author 邓立瑶
     * @since 2018-11-25 11:46:57
     */
    @ApiOperation(value = "查询model")
    @GetMapping(value = "/selTempModel/{templateId}")
    public ItooResult selTempModel(@PathVariable String templateId) {
        if (StringUtils.isEmpty(templateId)) {
            return ItooResult.build(ItooResult.FAIL, "模板id不能为空！");
        }
        try {
            TemplateModel templateModel = templateService.selectTempModel(templateId);
            return ItooResult.build(ItooResult.SUCCESS, "查询成功！", templateModel);
        } catch (Exception e) {
            return ItooResult.build(ItooResult.FAIL, "查询失败！");
        }
    }

    /**
     * 根据模板名称模糊查询template（限制操作人）
     *
     * @param name     模板名称
     * @param pageNo   页码
     * @param pageSize 页数
     * @param operator 操作人
     * @return 模糊查询的template
     * @author 任晓帅
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据模板名称模糊查询template（限制操作人）", notes = "分页根据模板名称模糊查询template（限制操作人）")
    @GetMapping(value = "queryTemplateByLikeNameAndOperator/{operator}/{pageNo}/{pageSize}")
    public ItooResult queryTemplateByLikeNameAndOperator(
            @RequestParam(required = false, defaultValue = "") String name,
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
            @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize) {
        PageInfo<TemplateEntity> templateList = templateService.queryTemplateByLikeNameAndOperator(name, operator, pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateList);
    }

    /**
     * 查询填空题控数
     *
     * @param questionTypeId     题型id
     * @param questionClassifyId 试题分类id
     * @param courseId           课程id
     * @return 查询填空题控数
     * @author 杨海云
     * @since 2.0.0 2018-11-15 19:40:28
     */

    @ApiOperation(value = "查询填空题控数")
    @GetMapping(value = "/queryCompletion/{questionTypeId}/{operator}/{courseId}")
    public ItooResult queryCompletion(
            @ApiParam(value = "题型id", required = true) @PathVariable String questionTypeId,
            @ApiParam(value = "操作人", required = true) @PathVariable String operator,
            @RequestParam(required = false, defaultValue = "") String questionClassifyId,
            @ApiParam(value = "课程Id", required = true) @PathVariable String courseId
    ) {
        if (StringUtils.isEmpty(operator) && StringUtils.isEmpty(questionTypeId)) {
            return ItooResult.build(ItooResult.FAIL, "题型和试题分类不可以为空", null);
        }
        List<Integer> completionNum = templateService.queryCompletion(questionTypeId, operator, questionClassifyId, courseId);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", completionNum);
    }

    /**
     * 查询试题类别
     *
     * @param courseId 课程id
     * @return 查询试题类别
     * @author 杨海云
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "查询试题类别")
    @GetMapping(value = "/queryQuestionType/{courseId}/{operator}")
    public ItooResult queryQuestionType(
            @PathVariable String courseId,
            @PathVariable String operator

    ) {
        if (StringUtils.isEmpty(courseId)) {
            return ItooResult.build(ItooResult.FAIL, "传递courseId不可以为空", null);
        }
        List<QuestionTypeModel> questionTypeModelList = templateService.queryQuestionType(courseId, operator);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", questionTypeModelList);
    }

    /**
     * 根据id更新template表状态
     *
     * @param id     templateId
     * @param status 状态
     * @return 根据id更新template表
     * @author 杨海云
     * @since 2.0.0 2018-11-15 19:40:28
     */
    @ApiOperation(value = "根据id更新template表")
    @PostMapping(value = "/updataTemplate/{id}/{status}")
    public ItooResult updataTemplate(
            @ApiParam(value = "id", required = true) @PathVariable String id,
            @ApiParam(value = "status", required = true) @PathVariable String status
    ) {
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(status)) {
            return ItooResult.build(ItooResult.FAIL, "更新失败", null);
        } else {
            boolean isUpdataTemplate = templateService.updataTemplate(id, status);
            return ItooResult.build(ItooResult.SUCCESS, "更新成功", isUpdataTemplate);
        }
    }

    /**
     * 随堂小连随机抽题插入方法
     *
     * @param templateModelList 模板,模板明细,模板明细必抽题
     * @return 返回true/false
     * @author 马莹
     * @since 2019-2-9 17:04:08
     */
    @ApiOperation(value = "随堂小连随机抽题插入方法")
    @PostMapping(value = "/installRandomQuestions")
    public ItooResult installRandomQuestions(@RequestBody TemplateModel templateModelList) {
        String templateId = templateService.installRandomQuestions(templateModelList);
        if (!"null".equals(templateId)) {
            return ItooResult.build(ItooResult.SUCCESS, "成功!", templateId);
        } else {
            return ItooResult.build(ItooResult.FAIL, "失败!");
        }
    }


    /**
     * 查询模板名称是否重复
     *
     * @param name
     * @return 模板名称是否重复
     * @author 贾建清
     * @since 2.0.0 2019-2-19 16:10:38
     */
    @ApiOperation(value = "查询模板名称是否重复")
    @GetMapping(value = "/queryTemplateName/{name}")
    public ItooResult queryTemplateName(@ApiParam(value = "name", required = true) @PathVariable String name) {
        List<TemplateModel> templateName = templateService.queryTemplateName(name);
        if (templateName.size() > 0) {
            return ItooResult.build(ItooResult.SUCCESS, "该模板名称重复,请重新填写", templateName);
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功!", templateName);
    }

    /**
     * 根据id删除template表
     *
     * @param id templateId
     * @return ITOO
     * @author 郭凯
     * @since 2.0.0 2019-2-19 20:08:48
     */
    @ApiOperation(value = "根据id删除template表")
    @PostMapping(value = "/updateTemlateById/{id}")
    public ItooResult updateTemlateById(@ApiParam(value = "id", required = true) @PathVariable String id) {
        if (templateService.updateTemplateById(id)) {
            return ItooResult.build(ItooResult.SUCCESS, "更新成功");
        } else {
            return ItooResult.build(ItooResult.FAIL, "更新失败");
        }
    }

    /**
     * 替换Redis中的题目
     *
     * @param templateId templateId
     * @return ITOO
     * @author 郭凯
     * @since 2.0.0 2019-2-24 19:58:11
     */
    @ApiOperation(value = "替换Redis中的题目")
    @PostMapping(value = "/updateTemplateByQuestionId/{templateId}/{courseId}/{operator}/{newQuestionId}/{oldQuestionId}")
    public ItooResult updateTemplateByQuestionId(@ApiParam(value = "templateId", required = true) @PathVariable String templateId,
                                                 @ApiParam(value = "courseId", required = true) @PathVariable String courseId,
                                                 @ApiParam(value = "operator", required = true) @PathVariable String operator,
                                                 @ApiParam(value = "newQuestionId", required = true) @PathVariable String newQuestionId,
                                                 @ApiParam(value = "oldQuestionId", required = true) @PathVariable String oldQuestionId) {
        if (templateService.updateTemplateByQuestionId(templateId, courseId, operator, newQuestionId, oldQuestionId)) {
            return ItooResult.build(ItooResult.SUCCESS, "更新成功");
        } else {
            return ItooResult.build(ItooResult.FAIL, "更新失败");
        }
    }


    /**
     * 根据模板id查询模板信息
     *
     * @param id 模板id
     * @return 模板信息
     * @author 贾建清
     * @since 2.0.0 2019-2-26 17:12:46
     */
    @ApiOperation(value = "根据模板id查询模板信息")
    @GetMapping(value = "/queryTemplateInfo/{id}")
    public ItooResult queryTemplateInfo(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        if (StringUtils.isEmpty(id)) {
            return ItooResult.build(ItooResult.FAIL, "传递id不可以为空", null);
        }
        List<TemplateInfoModel> templateInfoModelList = templateService.queryTemplateInfo(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", templateInfoModelList);
    }

    /**
     * 根据前端试题id集合查询出所有试题的题干加选项，用于固定抽题试题回显。
     * @param ids
     * @return
     * @author 李青松
     * @since 2.0.0 2019年3月19日 14:59:09
     */
    @ApiOperation(value = "根据试题ID查询试题题干及选项")
    @PostMapping(value = "/queryByQuestionId")
    public ItooResult queryByQuestionId(@RequestBody String[] ids){
        // TODO
        List questionAddModels=templateService.queryByQuestionId(ids);
        return ItooResult.build(ItooResult.SUCCESS,"查询成功",questionAddModels);
    }

}